package com.epmis.epmis.controller;


import com.epmis.epmis.utils.zhenziSMS;
import com.wf.captcha.ArithmeticCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;



@Controller
public class CodeController {
    @CrossOrigin
    @GetMapping(value = "api/getcode")
    @ResponseBody
    public ResponseEntity<Object> getCode(){
        // 算术类型 https://gitee.com/whvse/EasyCaptcha
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(111, 36);
        // 几位数运算，默认是两位
        captcha.setLen(2);
        // 获取运算的结果
        String result ="";
        try {
            result = new Double(Double.parseDouble(captcha.text())).intValue()+"";
        }catch (Exception e){
            result = captcha.text();
        }

        // 验证码信息
        String finalResult = result;
        Map<String,Object> imgResult = new HashMap<String,Object>(2){{
            put("img", captcha.toBase64());
            put("result", finalResult);
        }};
        return ResponseEntity.ok(imgResult);
    }

    @Autowired
    private zhenziSMS sms;

    @RequestMapping("api/sms")
    @ResponseBody
    //获取短信剩余数量
    public Integer sms() throws Exception{
        Integer integer = sms.checkBalance();
        return integer;
    }

    @RequestMapping("api/sendMessage")
    @ResponseBody
    public Map<String, Object> sendMessage(@RequestBody HashMap<String,Object> map) throws Exception {
        String phone = (String) map.get("phone");
        return sms.sendMessage(phone,phone);
    }

    @RequestMapping("api/checkMessage")
    @ResponseBody
    public boolean checkMessage(@RequestBody HashMap<String,Object> map) throws Exception {
        String messageId = (String) map.get("messageId");
        String cacheCode = (String) map.get("cacheCode");
        return sms.checkMessage(messageId,cacheCode);
    }

}
